package com.bsoft.gol.hcs.his.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.base.BaseHisPlateformXmlRequest;
import com.bsoft.gol.hcs.base.BaseHisPlateformXmlResponse;
import com.bsoft.gol.hcs.base.MsgHeaderRequest;
import com.bsoft.gol.hcs.clinical.bean.req.*;
import com.bsoft.gol.hcs.clinical.bean.response.DrugInformationTotalResponse;
import com.bsoft.gol.hcs.clinical.bean.response.QueryDrugInformationResponse;
import com.bsoft.gol.hcs.clinical.bean.response.RecipeDrugstoreDataResponse;
import com.bsoft.gol.hcs.clinical.bean.response.RecipeDrugstoreResponse;
import com.bsoft.gol.hcs.clinical.bean.vo.DrugstoreDepartmentVo;
import com.bsoft.gol.hcs.clinical.bean.vo.DrugstoreInfo;
import com.bsoft.gol.hcs.enumcase.InspectionEmum;
import com.bsoft.gol.hcs.enumcase.PrescriptionTypeEnum;
import com.bsoft.gol.hcs.his.bean.historydrug.QueryDrugResp;
import com.bsoft.gol.hcs.his.service.IElectronicMedicalHisService;
import com.bsoft.gol.hcs.utils.*;
import ctd.controller.exception.ControllerException;
import ctd.util.exception.CodedBaseRuntimeException;
import ctd.util.xml.jaxb.JAXBUtils;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import org.atag.util.http.KdHttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.List;

import static com.bsoft.gol.hcs.utils.CheckAppointmentUtil.getJsonDataFromPlatform;
import static com.bsoft.gol.hcs.utils.CheckAppointmentUtil.mapToXml;

/**
 * @Description: 电子病历相关his接口
 * @Author: zhaorb
 * @Date: 2020/8/20 14:25
 **/
@Service
public class ElectronicMedicalHisServiceImpl implements IElectronicMedicalHisService {
    private final static Logger log = LoggerFactory.getLogger(ElectronicMedicalHisServiceImpl.class);
    private String projectSource ="GOL";
    @Value("${platform_url}")
    public String platformUrl;

    @Override
    public BaseResponse<DrugInformationTotalResponse> queryHisDrugInformation(QueryDrugInformationRequest request) {
        if (request.getDrugType().contains(PrescriptionTypeEnum.WESRERN_MEDICINE.getCode())) {
            request.setPharmacyCode("11");
        } else if (PrescriptionTypeEnum.CHINESE_PATENT_MEDICINE.getCode().equals(request.getDrugType())) {
            request.setPharmacyCode("12");
        } else {
            request.setPharmacyCode("13");
        }
        log.info("ElectronicMedicalHisServiceImpl.queryHisDrugInformation入参：{}", request);
        BaseResponse<DrugInformationTotalResponse> result = new BaseResponse<>();
        //入参转换开始-zrb
        String drugType = request.getDrugType();
        if (drugType.contains(PrescriptionTypeEnum.WESRERN_MEDICINE.getCode())) {
            request.setDrugType(PrescriptionTypeEnum.WESRERN_MEDICINE.getCode());
        }
        if (CommonUtils.isNotEmpty(request.getKeyWord())) {
            request.setKeyWord(request.getKeyWord().toUpperCase());
        }
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        jsonParams.put("organizationId", jsonParams.remove("hospitalCode"));
        //入参转换结束
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(Constants.HIS_CLIENT_URL_01
                + Constants.SYNC_DRUG_INFORMATION, jsonParams);
        log.info("PrescriptionServiceImpl.queryHisDrugInformation 第三方返回数据:{}", jsonObject);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                DrugInformationTotalResponse response = new DrugInformationTotalResponse();
                response.setTotal(BigInteger.valueOf(Long.parseLong(data.get("total").toString())));
                List<QueryDrugInformationResponse> queryDrugInformationResponseList = JSONObject.parseArray(
                        data.get("list").toString(), QueryDrugInformationResponse.class);
                response.setList(queryDrugInformationResponseList);
                result.setData(response);
            } else {
                result.setCode(jsonObject.getInteger("code"));
                result.setMessage(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(ResultCode.ERROR);
        }
        log.info("ElectronicMedicalHisServiceImpl.queryHisDrugInformation出参：{}", result);
        return result;
    }

    /**
     * @description: 医院平台获取药房药品信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/2 17:29
     * @param: request
     * @return: org.atag.core.base.BaseResponse<clinical.bean.response.DrugInformationTotalResponse>
     */
    @Override
    public BaseResponse<DrugInformationTotalResponse> queryHisPlateformDrugInformation(QueryDrugInformationRequest request) {
        log.info("WebCloudClinicServiceImpl.queryHisPlateformDrugInformation 入参：{}", request);
        BaseResponse<DrugInformationTotalResponse> result = new BaseResponse<>();
        String drugType = request.getDrugType();
        if (drugType.contains(PrescriptionTypeEnum.WESRERN_MEDICINE.getCode())) {
            request.setDrugType(PrescriptionTypeEnum.WESRERN_MEDICINE.getCode());
        }
        if (CommonUtils.isNotEmpty(request.getKeyWord())) {
            request.setKeyWord(request.getKeyWord().toUpperCase());
        }

        String serviceName = InspectionEmum.SyncDrugInformation.getCode();

        //组装xml请求入参
        BaseHisPlateformXmlRequest<GetDrugsMsgBodyRequest> xmlRequest = new BaseHisPlateformXmlRequest<GetDrugsMsgBodyRequest>();
        //组装MsgHeader
        MsgHeaderRequest msgHeader = new MsgHeaderRequest();
        msgHeader.setMsgType(InspectionEmum.SyncDrugInformation.getValue());
        msgHeader.setMsgVersion(Constants.MSG_VERSION);
        msgHeader.setOrganization(request.getHospitalCode());
        msgHeader.setSender(projectSource);
        msgHeader.setServiceType(Constants.SERVICE_TYPE_SERVICE);
        xmlRequest.setMsgHeader(msgHeader);
        //组装MsgBody
        GetDrugsMsgBodyRequest getDrugsMsgBodyRequest = new GetDrugsMsgBodyRequest();
        if(CommonUtils.isNotEmpty(request.getKeyWord())){
            request.setKeyWord(request.getKeyWord().toLowerCase());
        }
        //医院平台入参
        getDrugsMsgBodyRequest.setHospitalCode(request.getHospitalCode());
        getDrugsMsgBodyRequest.setDrugType(request.getDrugType());
        getDrugsMsgBodyRequest.setKeyWord(request.getKeyWord());
        getDrugsMsgBodyRequest.setPharmacyCode(request.getPharmacyCode());
        getDrugsMsgBodyRequest.setPageNo(request.getPageNo());
        getDrugsMsgBodyRequest.setPageSize(request.getPageSize());

        QueryDrugInformationWhisRequest queryDrugInformationWhisRequest = new QueryDrugInformationWhisRequest();
        BeanUtils.copyProperties(request, queryDrugInformationWhisRequest);
        //处方平台入参
        getDrugsMsgBodyRequest.setQueryData(request);
        //WHIS入参
        getDrugsMsgBodyRequest.setData(queryDrugInformationWhisRequest);
        xmlRequest.setMsgBody(getDrugsMsgBodyRequest);

        String queryXml = JAXBUtils.object2Xml(new Class[]{BaseHisPlateformXmlRequest.class, GetDrugsMsgBodyRequest.class}, xmlRequest);

        try {
            //组装soapXml数据
            queryXml = WhisClientUtil.getSoapXmlWithOutBSXml(serviceName, queryXml);
            String xmlStr = WhisClientUtil.getStringDataFromPhis(platformUrl,queryXml);
            BaseHisPlateformXmlResponse xmlResponse = CheckAppointmentUtil.getBaseHisPlateformXmlResponse(xmlStr);
            if (null != xmlResponse) {
                //转换数据返回的data字符串
                xmlResponse = JSONObject.parseObject(JSONObject.toJSON(xmlResponse).toString(), BaseHisPlateformXmlResponse.class);

                if (null != xmlResponse) {
                    BaseHisPlateformXmlResponse.MsgBody msgBody = xmlResponse.getMsgBody();

                    if (msgBody != null) {
                        String status = msgBody.getStatus();

                        if (status != null && "true".equals(status)) {
                            if(null != msgBody.getData()){
                                String data = String.valueOf(xmlResponse.getMsgBody().getData());
                                if (CommonUtils.isNotEmpty(data)) {
                                    DrugInformationTotalResponse drugInformationTotalResponse = JAXBUtils.xml2Object(data, DrugInformationTotalResponse.class);
                                    if (CommonUtils.isNotEmpty(drugInformationTotalResponse)) {
                                        result.setData(drugInformationTotalResponse);
                                    }
                                }
                            }
                        } else {
                            throw new CodedBaseRuntimeException(201, msgBody.getDetail());
                        }
                    } else {
                        throw new CodedBaseRuntimeException(201, "获取药房药品信息失败！");
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setCode(ResultCode.ERROR);
            result = BaseRespUtil.setResultError("获取药房药品信息失败");

        }
        log.info("WebCloudClinicServiceImpl.getHisPlateformDrugUsage 出参：{}", result);
        return result;
    }


    /**
     * 获取his药房代码
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse<DrugstoreInfo> recipeDrugstore(RecipeDrugstoreRequest request) {
        BaseResponse<DrugstoreInfo> response = new BaseResponse<DrugstoreInfo>();

        LinkedHashMap<String, String> msgHeaderMap = new LinkedHashMap();
        msgHeaderMap.put("Sender", "HOL/GOL");
        msgHeaderMap.put("MsgType", "PTS_1001");
        msgHeaderMap.put("MsgVersion", "3.3.03");
        String msgHeaderXml = mapToXml(msgHeaderMap, "MsgHeader");

        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("VisitOrganization", request.getDepartment().getVisitOrganization());
        queryConditions.put("DeptId", request.getDepartment().getDeptId());
        queryConditions.put("EpitaxialSign", request.getDepartment().getEpitaxialSign());
        String queryConditionsXml = mapToXml(queryConditions, "Department");
        String serviceName = "webCloudClinic/recipeDrugstore";

        try {
            String xmlStr = getJsonDataFromPlatform(Constants.HIS_DRUGSTORE_URL + serviceName, serviceName, msgHeaderXml, queryConditionsXml);
            RecipeDrugstoreResponse res = JAXBUtils.xml2Object(xmlStr, RecipeDrugstoreResponse.class);
//            JSONObject jsonObject = JSONObject.parseObject(jsonBSXmlStr);
//            String strBSXml = jsonObject.getString("BSXml");
//            ReasonAndWarningHisResponse res = JSONObject.parseObject(strBSXml, ReasonAndWarningHisResponse.class);
            if (res.getMsgHeader() != null) {
                String status = res.getMsgHeader().getStatus();
                if (status != null && "true".equals(status)) {
                    //返回成功
                    response.setData(res.getDrugstoreInfo());
                } else {
                    response.setCode(ResultCode.ERROR);
                    response = BaseRespUtil.setResultError(res.getMsgHeader().getDetail());
                }
            } else {
                response.setCode(ResultCode.ERROR);
                response = BaseRespUtil.setResultError("his回头信息Header为空！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ResultCode.ERROR);
            response = BaseRespUtil.setResultError("his请求" + serviceName + "接口异常");

        }
        return response;
    }

    /**
     * 医院平台获取药房代码
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse<DrugstoreInfo> hisPlateformRecipeDrugstore(RecipeDrugstoreRequest request) {
        BaseResponse<DrugstoreInfo> response = new BaseResponse<DrugstoreInfo>();
        String serviceName = InspectionEmum.RecipeDrugstore.getCode();

        DrugstoreDepartmentVo department = request.getDepartment();

        //组装xml请求入参
        BaseHisPlateformXmlRequest<RecipeDrugstoreRequest> xmlRequest = new BaseHisPlateformXmlRequest<RecipeDrugstoreRequest>();
        //组装MsgHeader
        MsgHeaderRequest msgHeader = new MsgHeaderRequest();
        msgHeader.setMsgType(InspectionEmum.RecipeDrugstore.getValue());
        msgHeader.setMsgVersion(Constants.MSG_VERSION);
        msgHeader.setOrganization(department.getVisitOrganization());
        msgHeader.setSender(projectSource);
        msgHeader.setServiceType(Constants.SERVICE_TYPE_SERVICE);
        xmlRequest.setMsgHeader(msgHeader);

        xmlRequest.setMsgBody(request);
        String queryXml = JAXBUtils.object2Xml(new Class[]{BaseHisPlateformXmlRequest.class, RecipeDrugstoreRequest.class}, xmlRequest);

        try {
            queryXml = WhisClientUtil.getSoapXmlWithOutBSXml(serviceName, queryXml);
            String xmlStr = WhisClientUtil.getStringDataFromPhis(platformUrl, queryXml);
            BaseHisPlateformXmlResponse xmlResponse = JAXBUtils.xml2Object(xmlStr, BaseHisPlateformXmlResponse.class);
            if(null != xmlResponse){
                //转换数据返回的data字符串
                xmlResponse = JSONObject.parseObject(JSONObject.toJSON(xmlResponse).toString(), BaseHisPlateformXmlResponse.class);
                if(null != xmlResponse){
                    BaseHisPlateformXmlResponse.MsgBody msgBody = xmlResponse.getMsgBody();
                    if (msgBody != null) {
                        String status = msgBody.getStatus();
                        if (status != null && "true".equals(status)) {
                            if(null != msgBody.getData()){

                                String data = String.valueOf(xmlResponse.getMsgBody().getData());
                                RecipeDrugstoreDataResponse res = JAXBUtils.xml2Object(data, RecipeDrugstoreDataResponse.class);
                                if(null != res){
                                    response.setData(res.getDrugstoreInfo());
                                }
                                //返回成功
                                response.setCode(200);
                            }
                        } else {
                            response.setCode(ResultCode.ERROR);
                            response = BaseRespUtil.setResultError(msgBody.getDetail());
                        }
                    } else {
                        response.setCode(ResultCode.ERROR);
                        response = BaseRespUtil.setResultError("获取药房代码失败");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ResultCode.ERROR);
            response = BaseRespUtil.setResultError("获取药房代码失败");

        }

        return response;
    }

    /**
     * @description: 医院平台获取药品信息
     * @param: request
     * @return: org.atag.core.base.BaseResponse<clinical.bean.response.DrugInformationTotalResponse>
     */
    @Override
    public QueryDrugResp queryDrugInfoByCode(QueryDrugInformationRequest request) throws ControllerException {
        log.info("queryDrugInfoByCode 医院平台获取药品信息入参：{}", request);
        QueryDrugResp queryDrugResp = new QueryDrugResp();
        if (CommonUtils.isNotEmpty(request.getKeyWord())) {
            request.setKeyWord(request.getKeyWord().toUpperCase());
        }
        String serviceName = InspectionEmum.SyncQueryDrug.getCode();

        //组装xml请求入参
        BaseHisPlateformXmlRequest<QueryDrugRequest> xmlRequest = new BaseHisPlateformXmlRequest<QueryDrugRequest>();
        //组装MsgHeader
        MsgHeaderRequest msgHeader = new MsgHeaderRequest();
        msgHeader.setMsgType(InspectionEmum.SyncQueryDrug.getValue());
        msgHeader.setOrganization(request.getHospitalCode());
        msgHeader.setMsgVersion(Constants.MSG_VERSION);
        msgHeader.setServiceType(Constants.SERVICE_TYPE_SERVICE);
        msgHeader.setSender(projectSource);
        xmlRequest.setMsgHeader(msgHeader);
        //组装MsgBody
        QueryDrugRequest queryDrugRequest = new QueryDrugRequest();
        //医院平台入参
        queryDrugRequest.setVisitOrganization(request.getHospitalCode());
        queryDrugRequest.setInputCode(request.getKeyWord());
        queryDrugRequest.setDrugType(request.getDrugType());
        queryDrugRequest.setPageSize(request.getPageSize());
        queryDrugRequest.setPageNo(request.getPageNo());
        //组装MsgBody
        xmlRequest.setMsgBody(queryDrugRequest);

        String queryXml = JAXBUtils.object2Xml(new Class[]{BaseHisPlateformXmlRequest.class, QueryDrugRequest.class}, xmlRequest);

        try {
            //组装soapXml数据
            queryXml = WhisClientUtil.getSoapXmlWithOutBSXml(serviceName, queryXml);
            String xmlStr = WhisClientUtil.getStringDataFromPhis(platformUrl,queryXml);
            BaseHisPlateformXmlResponse xmlResponse = CheckAppointmentUtil.getBaseHisPlateformXmlResponse(xmlStr);
            if (null != xmlResponse) {
                //转换数据返回的data字符串
                xmlResponse = JSONObject.parseObject(JSONObject.toJSON(xmlResponse).toString(), BaseHisPlateformXmlResponse.class);

                if (null != xmlResponse) {
                    BaseHisPlateformXmlResponse.MsgBody msgBody = xmlResponse.getMsgBody();
                    if (msgBody != null) {
                        String status = msgBody.getStatus();

                        if (status != null && "true".equals(status)) {
                            if(null != msgBody.getData()){
                                String data = String.valueOf(xmlResponse.getMsgBody().getData());
                                if (CommonUtils.isNotEmpty(data)) {
                                    queryDrugResp = JAXBUtils.xml2Object(data, QueryDrugResp.class);
                                }
                            }
                        } else {
                            throw new CodedBaseRuntimeException(201, msgBody.getDetail());
                        }
                    } else {
                        throw new CodedBaseRuntimeException(201, "获取药品信息失败！");
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ControllerException("获取药品信息失败！");
        }
        log.info("queryDrugInfoByCode 出参：{}", JSONObject.toJSON(queryDrugResp));
        return queryDrugResp;
    }

}
